package juc.ForkJoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @author 况祥彬
 * @date 2020/12/11 18:12
 **/
class MyForkJoin extends RecursiveTask<Integer> {
    private static final Integer MAX = 200;
    private int startValue;
    private int endValue;

    public MyForkJoin(int startValue, int endValue) {
        this.endValue = endValue;
        this.startValue = startValue;
    }

    @Override
    protected Integer compute() {
// 如果条件成立，说明这个任务所需要计算的数值分为足够小了,可以正式进行累加计算了
        if (endValue - startValue < MAX) {
            System.out.println("开始计算的部分：startValue = " + startValue + ";endValue = " + endValue);
            Integer totalValue = 0;
            for (int index = this.startValue; index <= this.endValue; index++) {
                totalValue += index;
            }
            return totalValue;
        } else {
            // 否则再进行任务拆分，拆分成两个任务
            MyForkJoin forkJoinTask1 = new MyForkJoin(startValue, (startValue + endValue) / 2);
            forkJoinTask1.fork();
            MyForkJoin forkJoinTask2 = new MyForkJoin((startValue + endValue) / 2 + 1, endValue);
            forkJoinTask2.fork();
            //效率高些，因为task1和task2可以并发执行，而fork只能一个一个的执行
            //invokeAll(forkJoinTask1,forkJoinTask2);
            return forkJoinTask1.join() + forkJoinTask2.join();

        }
    }
}
public class demo1 {
    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Integer> forkJoinTask = forkJoinPool.submit(new MyForkJoin(1, 1000));
        try {
            Integer result = forkJoinTask.get();
            System.out.println(result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

